<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of PostModel
 * 文章关联模型
 * @author yihua
 */

namespace Common\Model;

use Think\Model;

class PostModel extends Model {

    protected $model = null;
    protected $view = '';
    //验证规则项
    protected $_validate = array(
        array('post_title', 'require', '请输入文章标题', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('post_content', 'require', '请输入文章内容', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('post_content_html', 'require', '请输入文章内容', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH)
    );
    //自动添加项
    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('modify_time', NOW_TIME, self::MODEL_BOTH)
    );

    /**
     * 加载文章列表
     */
    public function loadList($map) {
        $this->model = $this->model ? $this->model : D('PostView')->setView($this->view);
        $options = $this->options;
        if (!empty($this->view)) {
            $list['count'] = count($this->model->where($map)->group('post_id')->field('post_id')->select());
            $list['page'] = loadPage($list['count'], $options['limit']);
            $this->model->options = $options;
            $list['list'] = $this->model->where($map)->group('post_id')->select();
        } else {
            $this->options = array();
            $list['count'] = $this->model->where($map)->field('post_id')->count();
            $list['page'] = loadPage($list['count'], $options['limit']);
            $this->model->options = $options;
            $list['list'] = $this->model->where($map)->select();
        }
        return $list;
    }

    public function fetch($map) {
        $this->model = $this->model ? $this->model : D('PostView');
        $info = $this->model->setView($this->view)->where($map)->find();
        $info['item_id_arr'] = explode(',', $info['item_ids']);
        $info['tag_id_arr'] = explode(',', $info['tag_ids']);
        return $info;
    }

    public function view($view) {
        $this->view = $view;
        return $this;
    }

    function model($model) {
        $this->model = $model ? $model : $this;
        return $this;
    }

    public function insert($data) {
        //摘要生成
        $data['post_excerpt'] = $this->getExcerpt($data['post_content_html']);
        $specialImg = $this->getSpecialImg();
        if (!empty($specialImg)) {
            $data['special_img_path'] = $specialImg['path'];
            $data['special_img_id'] = $specialImg['id'];
        }
        $post = $this->create($data);
        if (empty($post)) {
            return false;
        }
        //插入成功
        if ($res = $this->add($post)) {
            $tags = explode(',', $data['tags']);
            $items = $data['item_ids'];
            $this->savePostItem($res, $items);
            $this->savePostTag($res, $tags);
            return $res;
        } else {
            return false;
        }
    }

    /**
     * 获取特殊的图片
     */
    public function getSpecialImg() {
        $upload = new \Think\Upload(array('savePath' => 'uploads/attach/'));
        $info = $upload->uploadOne($_FILES['special_img']);
        unset($info['key']);
        $data['id'] = M('media')->add($info);
        $data['path'] = $info['savepath'] . $info['savename'];
        return $data;
    }

    public function getExcerpt($content, $length = 400) {
        $content = html2text($content);
        return mb_substr($content, 0, $length);
    }

    /**
     * 添加日志分类
     */
    public function savePostItem($post_id, $item_ids, $act = 'insert') {
        if (is_string($item_ids)) {
            $items = explode(',', $item_ids);
        } elseif (is_array($item_ids)) {
            $items = $item_ids;
        } elseif (is_int($item_ids)) {
            $items[] = $item_ids;
        }
        if ($act != 'insert') {
            //已插入的tag
            $oldItemIds = M('post_item')->where(array('post_id' => $post_id))->getField('item_id', true);
            //这些是准备删除的
            $deleteItemIds = array_diff($oldItemIds, $items);
            M('item')->where(array('item_id' => array('in', $deleteItemIds)))->setDec('frequency', 1);
            M('post_item')->where(array('post_id' => $post_id, 'item_id' => array('in', $deleteItemIds)))->delete();
            //这些是准备插入的
            $items = array_diff($items, $oldItemIds);
        }
        foreach ($items as $key => $value) {
            $data[] = array(
                'post_id' => $post_id,
                'item_id' => $value
            );
        }
        M('post_item')->addAll($data, array(), true);
        M('Item')->where(array('item_id' => array('in', $items)))->setInc('frequency', 1);
    }

    /**
     * 保存文章标签
     * @param type $post_id
     * @param type $tags
     * @return boolean
     */
    public function savePostTag($post_id, $tags, $act = 'insert') {
        if (empty($tags)) {
            return true;
        } elseif (is_string($tags)) {
            $tags = explode(',', $tags);
        } elseif (is_array($tags)) {
            $tags = $tags;
        } elseif (is_int($tags)) {
            $tags[] = $tags;
        }
        //取出tag表中的数据
        $allTags = M('Tag')->getField('tag_name', true);
        //新添加的tag
        $newtag = array_diff($tags, $allTags);
        foreach ($newtag as $k => $v) {
            $add[] = array(
                'tag_name' => $v,
                'create_time' => time(),
                'modify_time' => time(),
                'alias' => urlencode($v)
            );
        }
        //插入tag表
        M('tag')->addAll($add);
        //取出所有的关于该文章的tagid
        $newTagIds = M('Tag')->where(array('tag_name' => array('in', $tags)))->getField('tag_id', true);
        if ($act != 'insert') {
            //已插入的tag
            $oldTagIds = M('post_tag')->where(array('post_id' => $post_id))->getField('tag_id', true);
            //这些是准备删除的
            $deleteTagIds = array_diff($oldTagIds, $newTagIds);
            M('tag')->where(array('tag_id' => array('in', $deleteTagIds)))->setDec('frequency', 1);
            M('post_tag')->where(array('post_id' => $post_id, 'tag_id' => array('in', $deleteTagIds)))->delete();
            //这些是准备插入的
            $newTagIds = array_diff($newTagIds, $oldTagIds);
        }
        foreach ($newTagIds as $k => $v) {
            $all[] = array(
                'tag_id' => $v,
                'post_id' => $post_id
            );
        }
        M('post_tag')->addAll($all);
        //频率加1
        M('tag')->where(array('tag_id' => array('in', $newTagIds)))->setInc('frequency', 1);
    }

}
